package com.sadam.ui4.FragmentCommentPage;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.Data.Comment;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;

import java.util.ArrayList;
import java.util.List;

public class FragmentCommentPage extends DialogFragment {

    private static final String ARG_VIDEO_ID = "video_id";
    private long videoId;

    private RecyclerView recyclerView;
    private EditText editTextComment;
    private Button buttonSend;
    private CommentAdapter commentAdapter;
    private MySqLiteOpenHelper dbHelper;
    private User currentUser;
    private TextView tvCommentCount;
    private ImageButton btnClose;

    private List<Comment> comments = new ArrayList<>();
    private boolean isLoading = false;
    private OnCommentPostedListener commentPostedListener;

    /**
     * 评论发布回调接口
     */
    public interface OnCommentPostedListener {
        void onCommentPosted();
    }
    /**
     * 设置评论发布监听器
     */
    public void setOnCommentPostedListener(OnCommentPostedListener listener) {
        this.commentPostedListener = listener;
    }
    public static FragmentCommentPage newInstance(long videoId) {
        Bundle args = new Bundle();
        args.putLong(ARG_VIDEO_ID, videoId);
        FragmentCommentPage fragment = new FragmentCommentPage();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle);

        try {
            if (getArguments() != null) {
                videoId = getArguments().getLong(ARG_VIDEO_ID);
                Log.d("FragmentCommentPage", "Video ID: " + videoId);

                if (videoId <= 0) {
                    Log.e("FragmentCommentPage", "Invalid video ID: " + videoId);
                    dismiss();
                    return;
                }
            } else {
                Log.e("FragmentCommentPage", "No arguments provided");
                dismiss();
                return;
            }

            // 初始化数据库帮助类
            dbHelper = new MySqLiteOpenHelper(requireContext(), MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);
            currentUser = User.getCurrentUser(requireContext(), dbHelper);

            if (currentUser == null) {
                Log.w("FragmentCommentPage", "No current user, comment functionality will be limited");
            } else {
                Log.d("FragmentCommentPage", "Current user: " + currentUser.getName());
            }
        } catch (Exception e) {
            Log.e("FragmentCommentPage", "Error in onCreate", e);
            if (isAdded()) {
                Toast.makeText(requireContext(), "初始化评论区失败", Toast.LENGTH_SHORT).show();
            }
            dismiss();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = null;
        try {
            view = inflater.inflate(R.layout.fragment_comment_page, container, false);
            initView(view);
        } catch (Exception e) {
            Log.e("FragmentCommentPage", "Error creating view", e);
            if (isAdded()) {
                Toast.makeText(requireContext(), "加载评论区失败", Toast.LENGTH_SHORT).show();
            }
        }
        return view;
    }

    private void initView(View view) {
        try {
            recyclerView = view.findViewById(R.id.recyclerView_comments);
            editTextComment = view.findViewById(R.id.editText_comment_content);
            buttonSend = view.findViewById(R.id.button_send_comment);
            tvCommentCount = view.findViewById(R.id.tvCommentCount);
            btnClose = view.findViewById(R.id.btnClose);

            // 检查视图是否成功初始化
            if (recyclerView == null) {
                throw new IllegalStateException("recyclerView is null");
            }
            if (editTextComment == null) {
                throw new IllegalStateException("editTextComment is null");
            }
            if (buttonSend == null) {
                throw new IllegalStateException("buttonSend is null");
            }
            if (tvCommentCount == null) {
                throw new IllegalStateException("tvCommentCount is null");
            }
            if (btnClose == null) {
                throw new IllegalStateException("btnClose is null");
            }

            // 初始化适配器
            commentAdapter = new CommentAdapter();
            recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
            recyclerView.setAdapter(commentAdapter);

            // 设置发送按钮点击事件
            buttonSend.setOnClickListener(v -> {
                if (isLoading) {
                    Toast.makeText(requireContext(), "正在发送，请稍候...", Toast.LENGTH_SHORT).show();
                    return;
                }

                String content = editTextComment.getText().toString().trim();
                if (content.isEmpty()) {
                    Toast.makeText(requireContext(), "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (content.length() > 500) {
                    Toast.makeText(requireContext(), "评论内容不能超过500字", Toast.LENGTH_SHORT).show();
                    return;
                }

                addComment(content);
            });

            // 设置关闭按钮点击事件
            btnClose.setOnClickListener(v -> {
                dismiss();
            });

            Log.d("FragmentCommentPage", "View initialization completed");

        } catch (Exception e) {
            Log.e("FragmentCommentPage", "Error initializing views", e);
            if (isAdded()) {
                Toast.makeText(requireContext(), "初始化评论区失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 延迟加载数据，确保视图完全创建
        view.postDelayed(() -> {
            if (isAdded() && !isLoading) {
                loadComments();
                loadCommentCount();
            }
        }, 100);
    }

    private void loadComments() {
        if (isLoading || dbHelper == null) return;

        isLoading = true;
        Log.d("FragmentCommentPage", "开始加载评论，视频ID: " + videoId);

        new Thread(() -> {
            try {
                List<Comment> loadedComments = dbHelper.getCommentsByVideoId(videoId);
                Log.d("FragmentCommentPage", "加载到 " + loadedComments.size() + " 条评论");

                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            comments.clear();
                            comments.addAll(loadedComments);
                            commentAdapter.setComments(comments);
                            isLoading = false;

                            // 显示空状态提示
                            if (loadedComments.isEmpty()) {
                                Toast.makeText(requireContext(), "暂无评论，快来发表第一条评论吧！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            } catch (Exception e) {
                Log.e("FragmentCommentPage", "加载评论失败", e);
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            isLoading = false;
                            Toast.makeText(requireContext(), "加载评论失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void loadCommentCount() {
        if (dbHelper == null) return;

        new Thread(() -> {
            try {
                int count = dbHelper.getVideoCommentCount(videoId);
                Log.d("FragmentCommentPage", "评论数量: " + count);

                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded() && tvCommentCount != null) {
                            tvCommentCount.setText(count + "条评论");
                        }
                    });
                }
            } catch (Exception e) {
                Log.e("FragmentCommentPage", "加载评论数量失败", e);
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded() && tvCommentCount != null) {
                            tvCommentCount.setText("0条评论");
                        }
                    });
                }
            }
        }).start();
    }

    private void addComment(String content) {
        if (currentUser == null) {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (dbHelper == null) {
            Toast.makeText(requireContext(), "数据库未初始化", Toast.LENGTH_SHORT).show();
            return;
        }

        isLoading = true;
        buttonSend.setEnabled(false);
        buttonSend.setText("发送中...");

        new Thread(() -> {
            try {
                Log.d("FragmentCommentPage", "开始插入评论，用户ID: " + currentUser.getId() + ", 视频ID: " + videoId);

                long commentId = dbHelper.insertComment(videoId, currentUser.getId(), content);
                Log.d("FragmentCommentPage", "评论插入完成，评论ID: " + commentId);

                if (commentId != -1) {
                    // 更新视频评论数
                    dbHelper.updateVideoCommentCount(videoId);

                    // 重新加载评论列表和评论数量
                    List<Comment> updatedComments = dbHelper.getCommentsByVideoId(videoId);
                    int newCommentCount = dbHelper.getVideoCommentCount(videoId);

                    if (getActivity() != null && !getActivity().isFinishing()) {
                        getActivity().runOnUiThread(() -> {
                            if (isAdded()) {
                                // 更新评论列表
                                comments.clear();
                                comments.addAll(updatedComments);
                                commentAdapter.setComments(comments);

                                // 更新评论数量
                                tvCommentCount.setText(newCommentCount + "条评论");

                                // 清空输入框
                                editTextComment.setText("");

                                // 恢复按钮状态
                                isLoading = false;
                                buttonSend.setEnabled(true);
                                buttonSend.setText("发送");

                                Toast.makeText(requireContext(), "评论成功", Toast.LENGTH_SHORT).show();

                                // 通知主页刷新（如果有需要）
                                if (requireActivity() instanceof MainActivity) {
                                    ((MainActivity) requireActivity()).refreshHomePage();
                                }

                                // ✅ 新增：触发评论发布回调
                                if (commentPostedListener != null) {
                                    commentPostedListener.onCommentPosted();
                                }


                                // 滚动到最新评论
                                if (!comments.isEmpty()) {
                                    recyclerView.smoothScrollToPosition(0);
                                }
                            }
                        });
                    }
                } else {
                    throw new Exception("评论插入失败，返回ID为-1");
                }
            } catch (Exception e) {
                Log.e("FragmentCommentPage", "评论失败", e);
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            isLoading = false;
                            buttonSend.setEnabled(true);
                            buttonSend.setText("发送");

                            String errorMessage = "评论失败";
                            if (e.getMessage() != null && e.getMessage().contains("空")) {
                                errorMessage = "评论内容不能为空";
                            } else if (e.getMessage() != null) {
                                errorMessage = "评论失败: " + e.getMessage();
                            }
                            Toast.makeText(requireContext(), errorMessage, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onStart() {
        super.onStart();

        // 设置对话框全屏
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            }
        }

        // 暂停首页视频
        if (requireActivity() instanceof MainActivity) {
            ((MainActivity) requireActivity()).pauseHomePageVideos();
        }

        Log.d("FragmentCommentPage", "Comment dialog started");
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);

        // 恢复首页视频
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).resumeHomePageVideos();
        }

        Log.d("FragmentCommentPage", "Comment dialog dismissed");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 清理资源
        if (commentAdapter != null) {
            commentAdapter.setComments(new ArrayList<>());
        }
        comments.clear();
        isLoading = false;

        Log.d("FragmentCommentPage", "Comment dialog view destroyed");
    }
}